package service

import (
	"golang.org/x/crypto/bcrypt"
	"strconv"
	"time"
	"zg3/config"
	"zg3/internal/api/request"
	"zg3/internal/models/dao"
	"zg3/pkg"
)

func UserRegister(register *request.UserRegister) (int, string) {
	password, _ := bcrypt.GenerateFromPassword([]byte(register.Password), bcrypt.DefaultCost)
	user := dao.User{
		QQCode:   register.QQCode,
		Password: string(password),
		NickName: register.QQCode,
		Remark:   "你好",
	}
	err := config.DB.Create(&user).Error
	if err != nil {
		return 0, "注册失败"
	}
	return int(user.ID), ""
}

func UserLogin(login *request.UserLogin) (string, string) {
	var user *dao.User
	Num := "login_password_bad" + login.QQCode
	Loc := "login_password_bad_loc" + login.QQCode
	err := config.DB.Where("qq_code=?", login.QQCode).Limit(1).Find(&user).Error
	if err != nil {
		return "", "用户不存在"
	}
	if user.ID == 0 {
		return "", "用户不存在"
	}
	get := config.Rdb.Get(config.Ctx, Num)
	cmd := config.Rdb.Get(config.Ctx, Loc)
	if cmd.Val() != "" {
		return "", "您多次登录失败，请稍后再试"
	}
	err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(login.Password))
	if err != nil {
		if get.Val() >= "3" {
			config.Rdb.Set(config.Ctx, Loc, "登录失败的锁", time.Minute*30)
			return "", "您多次登录失败，请稍后再试"
		}
		config.Rdb.Incr(config.Ctx, Num)
		config.Rdb.Expire(config.Ctx, Num, time.Minute*10)
		return "", "密码错误"
	}
	handler, _ := pkg.TokenHandler(strconv.Itoa(int(user.ID)))
	return handler, ""
}

func UserUpdate(update *request.UserUpdate, userId int) string {
	user := dao.User{
		HeardImage: update.HeardImage,
		NickName:   update.NickName,
		Remark:     update.Remark,
	}
	err := config.DB.Where("id=?", userId).Updates(&user).Error
	if err != nil {
		return "修改失败"
	}
	return ""
}
